<template>
  <div class="home">
    <div class="apptitle flex flex-jus-between">
      <!-- 查票 -->
      <div class="re">
        <input type="text" v-model="searchKey" @input="searchEmpty" placeholder="搜索公司信息" class="search-input" />
        <div class="search-btn" v-if="searchKey.length > 0" @click="handSearch"></div>
      </div>
    </div>
    <div class="card" v-for="item in companyList" :key="item.index" @click="companyInfoCopy(item)">
      <img src="../assets/icon-smsz.svg" class="logo">
      <dl>
        <dt>公司名称</dt>
        <dd>{{ item.gsmc }}</dd>
      </dl>
      <dl>
        <dt>纳税人识别号</dt>
        <dd>{{ item.companyno }}</dd>
      </dl>
    </div>
    <infinite-loading @infinite="updateList">
      <div slot="spinner">加载中...</div>
      <div slot="no-more">没有更多了</div>
    </infinite-loading>
    <div style="width: 100%;height:1.4rem;"></div>
    <div class="input-group">
      <button class="input" @click="uploadimg('camera')">
        <img src="../assets/icon-camera.svg">
        拍照录入
      </button>
      <button class="input" @click="uploadimg('album')">
        <img src="../assets/icon-album.svg">
        相册选择
      </button>
    </div>
  </div>
</template>

<script>
import InfiniteLoading from 'vue-infinite-loading';
import { mapMutations } from 'vuex';
import { media,getListInvoiceHeader } from "../plugins/api"
import { Toast } from 'vant-green'
export default {
  name: 'InitView',
  data(){
    return {
      code:'',
      userId:"",
      serverIdList:[],
      // 公司列表
      companyList:[
        // {
        //   companyName  :'青岛尚美数智酒店集团',
        //   companyNumber:'1234567890123'
        // },
      ] ,
      hasMore:true, // 当前加载状态状态
      currentPage:1,
      totalPages:1,
      searchKey:""
    }
  },
  components:{InfiniteLoading},
  methods:{
    ...mapMutations(["setFullLoading", "setTempInvoiceInputList"]),
    // 复制信息
    async companyInfoCopy(item){
      let str = `发票抬头：${item.gsmc}\r
发票类型：增值税专用发票
统一社会信用代码：${item.companyno}\r
开户银行名称：${item.fkyx}\r
基本开户账号：${item.yhzh}\r
注册场所地址：${item.address}\r
注册固定电话：${item.telphone}\r`
// 公司地址:
// 纳税人识别号:${item.companyno}\n
// 付款银行:${item.fkyx}\n
// 公司名称:${item.gsmc}\n
// 电话号码:
// 银行账号:${item.yhzh}
      // console.log(str);
      var input = document.createElement("textarea"); // 创建input对象
      input.value = str; // 设置复制内容
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      Toast('公司信息复制成功!')
      // try {
      //     // 请求读取权限
      //     await navigator.clipboard.writeText(str);
      //     Toast('公司信息复制成功!')
      // } catch (err) {
      //     console.error('Error copying text:', err);
      //     Toast('公司信息复制失败,请重试!')
      // }
    },
    toLink(url,params={}){
      this.$router.push({ path: url, query: params });
    },
    // 获取图片
    uploadimg(args){
      let _this = this
      this.$wechat.chooseImage({
          count: 9, // 最多几张
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: [args], // 可以指定来源是相册还是相机，默认二者都有 //'camera'拍照'album',相册
          defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。从3.0.26版本开始支持front和batch_front两种值，其中front表示默认为前置摄像头单拍模式，batch_front表示默认为前置摄像头连拍模式。（注：用户进入拍照界面仍然可自由切换两种模式）
          isSaveToAlbum: 0, //整型值，0表示拍照时不保存到系统相册，1表示自动保存，默认值是1
          success(res){
              _this.$store.commit('setFullLoading', true); // loading
              var localIds = res.localIds; // 返回选定照片的本地ID列表，
              _this.updateImg(localIds) // 上传图片到微信服务器
          },
          fail(err) {
            alert(`error:${JSON.stringify(err)}`)
            // 处理选择图片失败的逻辑
          }
      });
    },
    updateImg(arr){
      let _this = this;
      if(arr.length <= 0){
        // 没有图片了则开始上传
        const formData = new FormData()
              formData.append('type',"0") // 发票类型
              // 此处使用模拟数据 需要切换正式数据
              // 图片列表   _this.serverIdList
              formData.append('mediaIds',_this.serverIdList) //['3WGBdlGovN_3FFrKr_fin0CvqIfrxNNTC67ksA25aWEcCrVQiSxb-v774DfOZfxoE']
              formData.append('userId',localStorage.getItem('userId'))
        media(formData).then(res=>{
          this.$store.commit('setFullLoading',false)
          // 此处接口上传图片的id 后端去微信服务器拉图片 判断图片类型信息 
          // alert(`media:${JSON.stringify(res)}`)
          if(res.code == 200){
            // 如果可以识别则走ManualShow页面
            let arr = [...res.data]
            // console.log("arr:",arr);
            arr.map((v,i)=>{
              v.id = i
            })
            // 数据保存到vuex中
            _this.$store.commit('setTempInvoiceInputList',arr)
            _this.toLink('/manualShow')
          }else{
            // 返回值为是否无法识别 如果无法识别则走 error页面
            setTimeout(()=>{
              _this.toLink('/error',{errMsg:res.msg})
            },50)
          }
        }).catch((err)=>{
          // alert(`error:${JSON.stringify(err)}`)
          Toast(err.errMsg)
          this.$store.commit('setFullLoading',false)
        })
        return false;
      } 
      let element = arr.shift()
      this.$wechat.uploadImage({
        isShowProgressTips : 1, // 默认为1，显示进度提示
        localId            : element, // 需要上传的图片的本地ID，由chooseImage接口获得
        success            : function (res) {
          var serverId = res.serverId; // 返回图片的服务器端ID
          // 3FGtydLebC0X0nnv19vUfowJuMk4wEy5BZGaTZNMlNUURZEOsFi65ztcH6ix3rZXz
          _this.serverIdList.push(serverId)
          // 递归调用
          _this.updateImg(arr)
        }
      });
    },
    // 清空搜索框显示第一页数据
    searchEmpty(){
      if(this.searchKey == ''){
        this.currentPage = 1
        this.companyList = []
        this.updateList()
      }
    },
    // 搜索公司列表
    handSearch(){
      // 获取发票抬头
      this.currentPage = 1
      this.companyList = []
      // 如果为true则是没有全部加载完就点击了搜索
      if(this.hasMore || this.companyList.length <= 0){
        this.updateList()
      }else{
        this.state.reset()
      }
    },
    updateList($state){
      this.state = $state
      // 如果索引超过当前总页码则停止
      if(this.currentPage > this.totalPages){
        this.hasMore = false;
        if($state)$state.complete();
        return false;
      }
      // 获取发票抬头
      let params = {
        page      : this.currentPage,
        size      : 10,
        searchKey : this.searchKey
      }
      getListInvoiceHeader(params).then(res=>{
        console.log("获取发票抬头:",res);
        if(res.data.record){
          this.totalPages = res.data.totalPages // 总页数
          this.companyList = this.companyList.concat(res.data.record); // 获取来的列表数据
          this.currentPage++
          this.hasMore = true;
          if($state)$state.loaded();
        }else{
          this.hasMore = false;
          if($state)$state.complete();
          Toast('没有更多了!')
        }
      })
    },
  },
  mounted(){
    this.serverIdList = [] // 初始化清空
    this.$store.commit('setFullLoading',false)
    // 如果有userId则继续
    if(localStorage.getItem('userId')){
      this.userId = localStorage.getItem('userId')
    }else{
      // 没有就去登录
      localStorage.setItem('isAuthenticated',false)
      setTimeout(()=>{
        window.location.href = '/'
      },100)
    }
  }
}
</script>
<style scoped>
  .card {
    margin:0 auto 0.25rem;
    width: 7rem;
    height:2.86rem;
    background: url(../assets/card-bg1.png) no-repeat center center;
    background-size: 100% auto;
    padding:.4rem .35rem;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
    border-radius: 0.2rem;
  }
  .card:nth-of-type(n+1){
    background: url(../assets/card-bg1.png) no-repeat center center;
    background-size: 100% auto;
  }
  .card:nth-of-type(2n+1){
    background: url(../assets/card-bg2.png) no-repeat center center;
    background-size: 100% auto;
  }
  .card:nth-of-type(3n+1){
    background: url(../assets/card-bg3.png) no-repeat center center;
    background-size: 100% auto;
  }
  .card:nth-of-type(4n+1){
    background: url(../assets/card-bg4.png) no-repeat center center;
    background-size: 100% auto;
  }
  .card:nth-of-type(5n+1){
    background: url(../assets/card-bg5.png) no-repeat center center;
    background-size: 100% auto;
  }
  .card:nth-of-type(6n+1){
    background: url(../assets/card-bg6.png) no-repeat center center;
    background-size: 100% auto;
  }


  .card dl {
    color:white;
    letter-spacing: 0.01rem;
  }
  .card dt {
    font-size: .2rem;
    opacity: 0.7;
    margin-bottom: .08rem;
  }
  .card dd {
    font-size: .34rem;
  }
  .card .logo {
    position: absolute;
    right:.2rem;
    top:.2rem;
    width:1.3rem;
    opacity: 0.9;
  }
  .input-group {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    left:50%;
    bottom:1.6rem;
    transform: translateX(-50%);
    z-index: 9;
    width: 7.5rem;
    padding:0 .8rem
  }
  button.input {
    padding: 0.15rem 0.4rem;
    border: none;
    outline: none;
    color: rgb(255, 255, 255);
    background: #111;
    cursor: pointer;
    position: relative;
    z-index: 0;
    border-radius: .5rem;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    font-size: .3rem;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  button.input img {
    display: block;
    width:.5rem;
    margin-right: .2rem;
    opacity: 0.8;
  }
  button.input:before {
    content: "";
    background: linear-gradient(
      45deg,
      #415bf6,
      #856ff6,
      #7a00ff,
      #002bff
    );
    /* background: linear-gradient(
      45deg,
      #ff0000,
      #ff7300,
      #fffb00,
      #48ff00,
      #00ffd5,
      #002bff,
      #7a00ff,
      #ff00c8,
      #ff0000
    ); */
    position: absolute;
    top: -.02rem;
    left: -.02rem;
    background-size: 400%;
    z-index: -1;
    filter: blur(.2rem);
    -webkit-filter: blur(.2rem);
    width: calc(100% + .04rem);
    height: calc(100% + .04rem);
    animation: glowing-button-85 30s linear infinite;
    transition: opacity 0.3s ease-in-out;
    border-radius: 1rem;
  }

  @keyframes glowing-button-85 {
    0% {
      background-position: 0 0;
    }
    50% {
      background-position: 400% 0;
    }
    100% {
      background-position: 0 0;
    }
  }
  button.input:after {
    z-index: -1;
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    background: #333;
    left: 0;
    top: 0;
    border-radius: 1rem;
  }

  .testdiv {
    /* display: none; */
    width: 5rem;
    overflow: hidden;
    color:black;
    background-color: aqua;
    white-space: pre-wrap;
  }
  .handinput {
    font-size: 0.3rem;
    text-align: center;
    margin:.25rem auto 0;
  }
  .infinite-loading-container {
    font-size: .2rem;
    color:#999;
  }
  .search-input {
    border-radius: 100rem;
    border: 1px solid #ccc;
    font-size: .28rem;
    width: 6.5rem;
    margin-left:0.2rem;
    height: 0.6rem;
    padding: 0 .15rem;
    line-height: 1;
    text-align: center;
    font-weight: 400;
    color: #999;
    outline: none;
    appearance: none;
    display: block;
  }
  .re {
    position: relative
  }
  .search-btn {
    position: absolute;
    right:.0;
    top:0;
    z-index:2;
    width: .8rem;
    height:100%;
    background: url(../assets/icon-search.svg) no-repeat center center;
    background-size: 50% auto;
  }

</style>